using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Xml;
using Common.Utilities;
using Common.Utilities.Dispatcher;
using Common.Utilities.DLR;
using Workflows.Components.DALC;

namespace Workflows.Components
{
    /// <summary></summary>
    public class GlobalVariableSetterWorker:IWorker
    {
        private Thread _WorkerThread;
        private GlobalVariableSetterInstruction _Instruction;
        private GlobalVariableSetterOutput _Output;
        private RunContext _Context;
        private Guid _TicketID;
        private string _WorkflowName;
        private string _ComponentName;

        /// <summary>
        /// 
        /// </summary>
        public string ComponentName
        {
            get { return _ComponentName; }
        }

        /// <summary>
        /// 
        /// </summary>
        public string WorkflowName
        {
            get { return _WorkflowName; }
        }

        /// <summary></summary>
        public Thread WorkerThread
        {
            get { return _WorkerThread; }
        }

        /// <summary></summary>
        public InstructionBase Instruction
        {
            get { return _Instruction; }
        }

        /// <summary></summary>
        public ResultBase Output
        {
            get { return _Output; }
        }

        /// <summary></summary>
        public Type ComponentType
        {
            get { return typeof(GlobalVariableSetterComponent); }
        }

        /// <summary></summary>
        public RunContext Context
        {
            get { return _Context; }
            set { _Context = value; }
        }

        /// <summary></summary>
        public void SetInstruction(Guid ticketGuid, InstructionBase request, string workflowName, string componentName)
        {
            this._TicketID = ticketGuid;
            this._Instruction = (GlobalVariableSetterInstruction) request;
            this._WorkflowName = workflowName;
            this._ComponentName = componentName;
        }

        /// <summary></summary>
        public void SetInstruction(RunContext context, Guid ticketGuid, InstructionBase request, string workflowName, string componentName)
        {
            this._Context = context;
            this._TicketID = ticketGuid;
            this._Instruction = (GlobalVariableSetterInstruction)request;
            this._WorkflowName = workflowName;
            this._ComponentName = componentName;
        }

        /// <summary></summary>
        public void DoWork()
        {
            if (this.WorkerStartedEvent != null)
                this.WorkerStartedEvent(this._TicketID, this, this.GetType(), this._Instruction);

            this._WorkerThread = Thread.CurrentThread;
            this.SaveGlobalVariables();
        }

        /// <summary></summary>
        public void DoWorkAsync()
        {
            if (this.WorkerStartedEvent != null)
                this.WorkerStartedEvent(this._TicketID, this, this.GetType(), this._Instruction);

            this._WorkerThread = new Thread(new ThreadStart(this.SaveGlobalVariables));
            this._WorkerThread.Start();
        }

        /// <summary></summary>
        public void CancelWork()
        {
            if(this._WorkerThread !=null && this._WorkerThread.IsAlive)
            {
                this._WorkerThread.Abort();
                this._WorkerThread.Join();

                if(this.WorkerCancelledEvent !=null)
                {
                    this.WorkerCancelledEvent(this._TicketID, this.GetType(), this._Instruction);
                }
            }
        }

        public event WorkerStarted WorkerStartedEvent;
        public event WorkerFinished WorkerFinishedEvent;
        public event WorkerHasError WorkerErredEvent;
        public event WorkerCancelled WorkerCancelledEvent;
        public event WorkerStatusChanged WorkerStatusChangedEvent;

        #region save global variables
        private void SaveGlobalVariables()
        {
            try
            {
                Run run = RunDALC.GetRunByJob(this._TicketID);
                if(this._Context ==null || this._Context.Vars==null || this._Context.Vars.Count==0)
                {
                    List<GlobalVariable> vars = run.Vars;
                    this._Context=new RunContext(run.RunID,false,vars);
                }
                WorkflowDesign wfDesign = WorkflowDesignDALC.GetWorkflowDesignByRun(this._Context.RunID);
                if(this._Context.Vars !=null && this._Context.Vars.Count>0 &&
                    this._Instruction.Setters!=null && this._Instruction.Setters.Count>0)
                {
                    foreach(FieldSetter fieldSetter in this._Instruction.Setters)
                    {
                        for(int i=0;i<this._Context.Vars.Count;i++)
                        {
                            if(fieldSetter.TgtFieldName==this._Context.Vars[i].VarName)
                            {
                                if (this._Context.IsSubflow)
                                {
                                    this._Context.Vars[i].VarValue =
                                        SimpleDataTypeUtil.ReadValueAsString(this._Context.Vars[i].DataType,
                                                                             fieldSetter.SrcFieldValue);
                                }
                                else
                                {
                                    WorkflowComponentBase upstreamComponent =
                                        wfDesign.GetComponent(fieldSetter.SrcComponentID);
                                    Job upstreamJob =
                                        JobDALC.GetJobByRunAndComponent(this._Context.RunID, fieldSetter.SrcComponentID);
                                    string serializedUpstreamJobOutput = JobOutputDALC.GetJobOutput(upstreamJob.JobID);
                                    XmlDocument xDoc = new XmlDocument();
                                    xDoc.LoadXml(serializedUpstreamJobOutput);
                                    XmlNode xNode = xDoc.DocumentElement.ChildNodes[0];
                                    ResultBase upstreamOutput = upstreamComponent.Output;
                                    upstreamOutput = upstreamOutput.Instantiate(xNode);
                                    object upstreamFieldValue = upstreamOutput.ReadMemberValue(fieldSetter.SrcFieldName);
                                    if (!string.IsNullOrEmpty(fieldSetter.TransformationCodeSnippet))
                                    {
                                        GlobalVariable gVar = this._Context.Vars[i];
                                        List<MethodArgument> args = new List<MethodArgument>();
                                        Type gVarType = SimpleDataTypeUtil.ToSystemType(gVar.DataType);
                                        MethodArgument arg0 =
                                            new MethodArgument("gVarValue",
                                                               gVarType,
                                                               false,
                                                               SimpleDataTypeUtil.ReadDbValue(gVar.DataType,
                                                                                              gVar.VarValue));
                                        MethodArgument arg =
                                            new MethodArgument(
                                                "fromObj", upstreamFieldValue.GetType(), false, upstreamFieldValue);
                                        args.Add(arg0);
                                        args.Add(arg);
                                        MethodConstructInfo methodBuilder =
                                            new MethodConstructInfo(
                                                gVarType,
                                                "Convert",
                                                args, fieldSetter.TransformationCodeSnippet);
                                        upstreamFieldValue = CodeDomUtil.ExecuteMethod(methodBuilder);
                                    }
                                    this._Context.Vars[i].VarValue =
                                        SimpleDataTypeUtil.ReadValueAsString(this._Context.Vars[i].DataType,
                                                                             upstreamFieldValue);
                                }
                            }
                        }
                    }
                }

                if(!this._Context.IsSubflow)
                {
                    run.Vars = this._Context.Vars;
                    RunDALC.SaveRun(run);
                }
                this._Output=new GlobalVariableSetterOutput(this._Instruction.OwnerComponentID,this._TicketID, run.Vars);
                if(this.WorkerFinishedEvent !=null)
                {
                    this.WorkerFinishedEvent(this._TicketID, this.GetType(), this._Instruction, this._Output);
                }
            }
            catch(Exception ex)
            {
                if(this.WorkerErredEvent !=null)
                {
                    this.WorkerErredEvent(this._TicketID, this.GetType(), this._Instruction, ex.ToString(),true);
                }
            }
        }
        #endregion
    }
}


